Skip to main content

Safe File Deletion with Retries

Description

The safe_delete function attempts to delete a file, retrying if an error occurs. This is useful when deleting files that may be in use or locked, with a specified number of retries and delay between attempts.

Function Signature:

def safe_delete(file_path: str, retries: int = 5, delay: int = 1) -> None:

Parameters

  • file_path (str): The path to the file that should be deleted.
  • retries (int): The number of times to attempt the deletion if it fails. Default is 5 retries.
  • delay (int): The amount of time (in seconds) to wait between retries. Default is 1 second.

Returns

  • None: The function does not return any value.

Example Usage

safe_delete("/path/to/file.txt", retries=3, delay=2)

Notes

  • The function tries to delete the file up to the specified number of retries if an OSError occurs.
  • If the deletion is successful, a success message is printed. If all attempts fail, a failure message is printed.

Error Handling

  • If an OSError occurs during the deletion process (e.g., file is in use), the function retries the deletion after the specified delay. After the maximum retries, a failure message is printed.